package com.hankarun.gevrek;

import java.util.ArrayList;
import java.util.List;

import com.hankarun.gevrek.lib.DataSource;
import com.hankarun.gevrek.lib.MessageName;
import com.hankarun.gevrek.lib.ServerManager;
import com.hankarun.gevrek.lib.Tuple2;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;

public class MessageListActivity extends Activity {
	public static final String PREFS_NAME = "GevrekPrefs";
	protected ServerManager app;
	private ListView messagelist;
	public UserItemAdapter adapter;
	public int positions;
	private Tuple2 art;
	private String deletesender;
	private DataSource datasource;
	private List<MessageName> values;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_list);
        app = (ServerManager)getApplication();
        
        TextView toptext = (TextView) findViewById(R.id.groupnametext);
        toptext.setText(app.getGroup());
        
        messagelist = (ListView) findViewById(R.id.messagelistview);
        
        datasource = new DataSource(this);
		datasource.open();
		values = datasource.getAllMessage();
        datasource.close();
        
        
        ServerTask task = new ServerTask();
    	task.execute();
    	
    	Button newmessage = (Button) findViewById(R.id.newmessagebutton);
    	newmessage.setOnClickListener(new Button.OnClickListener() { 
        	public void onClick (View v){ 
        		Intent myIntent = new Intent(MessageListActivity.this, PostActivity.class);
        		myIntent.putExtra("reply",1);
        		MessageListActivity.this.startActivityForResult(myIntent, 0);
    		}
    	});
    	
    	ListView messages = (ListView) findViewById(R.id.messagelistview);
    	messages.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
		        datasource = new DataSource(MessageListActivity.this);
				datasource.open();
				datasource.createMessage(adapter.getItem(position).article.getArticleId());
		        datasource.close();
		        MessageName m = new MessageName();
		        m.setGroup(adapter.getItem(position).article.getArticleId());
		        values.add(m);
		        
				app.carticle = adapter.getItem(position);
				positions = position;

				for(int x = 0; x < adapter.getCount(); x++)
					adapter.getItem(x).visible = View.GONE;
				
				adapter.getItem(position).visible = View.VISIBLE;
				if(!adapter.getItem(position).bodyretrived){
			        ServerTask1 task = new ServerTask1();
			    	task.execute();
				}else{
					adapter.notifyDataSetChanged();
				}
			}
          });
    	
    }
    
	 private class ServerTask2 extends AsyncTask<Void, Void, Void> {
	    	private ProgressDialog dialog;
	    	@Override
	    	protected void onPreExecute(){
	    		dialog = ProgressDialog.show(MessageListActivity.this, "", 
	    				getString(R.string.deleting), true);
	    	}
	    	
	    	@Override
	    	protected void onPostExecute(Void s) {

	    	    dialog.dismiss();
	    	}

	    	@Override
	    	protected Void doInBackground(Void... params) {
	    		app.deleteArticle(app.carticle.article,deletesender);
	        	return null;
	    	}
	    }
    
	 private class ServerTask1 extends AsyncTask<Void, Void, String> {
	    	private ProgressDialog dialog;
	    	@Override
	    	protected void onPreExecute(){
	    		dialog = ProgressDialog.show(MessageListActivity.this, "", 
	    				getString(R.string.loading), true);
	    	}
	    	
	    	@Override
	    	protected void onPostExecute(String s) {
	    		int size = s.length();
	    		if(size > 150)
	    			size = 150;
	    		adapter.getItem(positions).bodyretrived = true;
	    		adapter.getItem(positions).bodys = s.substring(0, size)+ "...";
				adapter.notifyDataSetChanged();
	    	    dialog.dismiss();
	    	}

	    	@Override
	    	protected String doInBackground(Void... params) {	        
	        	return app.getBody(app.carticle.article.getArticleId());
	    	}
	    }

	 private class ServerTask extends AsyncTask<Void, Void, ArrayList<Tuple2>> {
	    	private ProgressDialog dialog;
	    	@Override
	    	protected void onPreExecute(){
	    		dialog = ProgressDialog.show(MessageListActivity.this, "", 
	    				getString(R.string.messagedownloadin), true);
	    	}
	    	
	    	@Override
	    	protected void onPostExecute(ArrayList<Tuple2> s) {
	    		adapter = new UserItemAdapter(MessageListActivity.this,   	
	            		android.R.layout.simple_list_item_1, s);
	    		messagelist.setAdapter(adapter);
	    	    dialog.dismiss();
	    	}

	    	@Override
	    	protected ArrayList<Tuple2> doInBackground(Void... params) {	        
	        	return app.iterateArticles();
	    	}
	    }
	 
	 public class UserItemAdapter extends ArrayAdapter<Tuple2> {
		    private ArrayList<Tuple2> users;
		
		    public UserItemAdapter(Context context, int textViewResourceId, ArrayList<Tuple2> users) {
		        super(context, textViewResourceId, users);
		        this.users = users;
		    }
		
		    @Override
		    public View getView(int position, View convertView, ViewGroup parent) {
		    	View v = convertView;
		    	if (v == null) {
		    		LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		            v = vi.inflate(R.layout.listitem, null);
		    	}
		      
		    	art = users.get(position);
	    		TextView subject = (TextView) v.findViewById(R.id.sbj);
	            TextView from = (TextView) v.findViewById(R.id.from);
	            TextView body = (TextView) v.findViewById(R.id.bodys);
	            
	            RelativeLayout rel = (RelativeLayout) v.findViewById(R.id.butreal);
	            
	            subject.setTextColor(0xfff00000);
	            
	            for(MessageName s : values)		         
	            	if(s.getGroup().equals(art.article.getArticleId().trim()))	            		
		            	subject.setTextColor(0xffffffff);
	            
	            
		    	if (art != null) {		            		        
		            subject.setText(art.toString());
			    	from.setText(art.parsedFrom);
			    	body.setText(art.bodys);
			    				    	
			    	body.setVisibility(art.visible);
			    	rel.setVisibility(art.visible);
			    	
			    	TextView reply = (TextView) v.findViewById(R.id.postText1);
			    	
			    	reply.setOnClickListener(new Button.OnClickListener() { 
			        	public void onClick (View v){ 
			        		Intent myIntent = new Intent(MessageListActivity.this, PostActivity.class);
			        		myIntent.putExtra("reply","0");
			        		MessageListActivity.this.startActivityForResult(myIntent, 0);
		        		}
		        	});
			    	
			    	TextView readmes = (TextView) v.findViewById(R.id.readText);

			    	readmes.setOnClickListener(new Button.OnClickListener() { 
			        	public void onClick (View v){ 
			        		Intent myIntent = new Intent(MessageListActivity.this, ReadMessage.class);
			        		MessageListActivity.this.startActivityForResult(myIntent, 0);
		        		}
		        	});
			    	
			    	TextView delete = (TextView) v.findViewById(R.id.deleteText1);

			    	if(art.visible == View.VISIBLE){
		                SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		                String username = settings.getString("username", "");
		                String pusername = app.carticle.article.getFrom();
		                if(!pusername.contains(username))
		                	delete.setVisibility(View.INVISIBLE);
		                else
		                	delete.setVisibility(View.VISIBLE);
			    	}
			    	
			    	delete.setOnClickListener(new Button.OnClickListener() { 
			        	public void onClick (View v){
			                SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
			                String username = settings.getString("username", "");
			                String pusername = app.carticle.article.getFrom();

			                if(pusername.contains(username)){
			                	deletesender = username+"@ceng.metu.edu.tr";
			                    AlertDialog.Builder alertDialog = new AlertDialog.Builder(
			                    		MessageListActivity.this);

			                    alertDialog.setPositiveButton(R.string.yes, new OnClickListener() {
			                        @Override
			                        public void onClick(DialogInterface dialog, int which) {
			            	            ServerTask2 task = new ServerTask2();
			            	        	task.execute();
			            	            ServerTask task1 = new ServerTask();
			            	        	task1.execute();
			            	            adapter.notifyDataSetChanged();
			                        }
			                    });

			                    alertDialog.setNegativeButton(R.string.no, null);

			                    alertDialog.setMessage(R.string.doyouwanttodeletemessage);
			                    alertDialog.setTitle(R.string.app_name);
			                    alertDialog.show();
				        		//Start the server and send the message	
			                }else{
			                	Toast.makeText(getApplicationContext(), R.string.deleteyourmessage , Toast.LENGTH_SHORT).show();
			                }			        		

		        		}
		        	});

		    	}
		    	return v;
		  }
	 }
	 
	    @Override
	    protected void onPause() {
	        super.onPause();

	        finish();
	    }
	    
	    @Override
	    protected void onStop() {
	        super.onPause();

	        finish();
	    }
	 
	    @Override
	    protected void onActivityResult(int requestCode, int resultCode, Intent data) {        
	        super.onActivityResult(requestCode, resultCode, data);
	        if(resultCode==1){       	
	            ServerTask task = new ServerTask();
	        	task.execute();
	            adapter.notifyDataSetChanged();
	        }
	    }
}

